package com.ljfiction.book.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.ToMessageBean;
import com.ljfiction.book.Dialog.IsOrNoDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.LoginActivity;
import com.ljfiction.book.activitys.MymessageActivity;
import com.ljfiction.book.activitys.ToEmailActivity;
import com.ljfiction.book.activitys.UserCenterActivity;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by admin on 2017/9/22.
 */

public class MyinformFragment extends BaseFragment {

    private RecyclerView myshupingrecycler;
    private SmartRefreshLayout refreshMyshupingrecycle;
    private int page = 1;
    private ToMessageBean toMessageBean;
    private List<ToMessageBean.DataBean.ListBean> datas = new ArrayList<>();
    private BaseQuickAdapter mAdapter;
    private Context context;
    private Intent intent;
    private LinearLayout layout;
    private NoBackgLodDialog noBackgLodDialog;
    private boolean isfirst = true;
    private IsOrNoDialog isOrNoDialog;
    private Torefresh torefresh;
    private boolean isIntData=false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        intdata();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myshuping_recycaler, null);
        myshupingrecycler = view.findViewById(R.id.myshupingrecycler);
        refreshMyshupingrecycle = view.findViewById(R.id.refresh_myshupingrecycle);
        layout = view.findViewById(R.id.zanwushuju);
        context = getContext();
        intView();
        return view;
    }

    private void intView() {
        myshupingrecycler.setAdapter(mAdapter = new BaseQuickAdapter<ToMessageBean.DataBean.ListBean, BaseViewHolder>(R.layout.mymessege_item, datas) {
            @Override
            protected void convert(BaseViewHolder helper, ToMessageBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.content_mymessage, item.getMessageContent())
                        .setText(R.id.mymessage_myname, item.getUserName())
                        .setText(R.id.mymessagetime, TimeTool.getTimeAndChange(String.valueOf(item.getDateTimes())));


                Glide.with(mContext).load(item.getUserHeadPortraitURL()).override(ScreenUtils.getNum(mContext,52),ScreenUtils.getNum(mContext,52)).into((ImageView) helper.getView(R.id.mymessage_muimage));

                if (item.getUserSex() == 0) {
                    ((ImageView) helper.getView(R.id.mymessage_sex)).setImageResource(R.mipmap.sex_n);
                } else {
                    ((ImageView) helper.getView(R.id.mymessage_sex)).setImageResource(R.mipmap.sex_v);
                }
                if (item.getUserId()==8184){
                    helper.getView(R.id.mymessage_sex).setVisibility(View.GONE);
                    helper.getView(R.id.mymessage_guanfang).setVisibility(View.VISIBLE);

                }else {
                    helper.getView(R.id.mymessage_sex).setVisibility(View.VISIBLE);
                    helper.getView(R.id.mymessage_guanfang).setVisibility(View.GONE);
                }
                if (item.getVipGrade() > 0) {
                    helper.getView(R.id.isvipimage_message).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.isvipimage_message).setVisibility(View.GONE);
                }
                if (item.getMessagesisRead() == 0) {
                    helper.getView(R.id.dian_mymessage).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.dian_mymessage).setVisibility(View.GONE);
                }
                helper.addOnClickListener(R.id.mymessage_muimage);
                helper.addOnClickListener(R.id.delet_mymessage);
            }
        });
        myshupingrecycler.setLayoutManager(new LinearLayoutManager(context));
        myshupingrecycler.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.mymessage_muimage:
                        if (datas.get(position).getUserId()==8184){
                            return;
                        }
                        intent = new Intent(context, UserCenterActivity.class);
                        intent.putExtra("userId", String.valueOf(datas.get(position).getUserId()));
                        startActivity(intent);
                        break;
                    case R.id.delet_mymessage:
                        if (isOrNoDialog == null) {
                            isOrNoDialog = new IsOrNoDialog(context, "删除与此人的私信？", true);
                            isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                                @Override
                                public void okClick() {
                                    OkHttpUtils.post(HttpManager.IP + "/person-delmessage")

                                            .params("userid", String.valueOf(datas.get(position).getUserId()))
                                            .params("senduserid", String.valueOf(datas.get(position).getSendUserId()))
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onSuccess(String s, Call call, Response response) {
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(s);
                                                        if (jsonObject.getInt("returnCode") == 200) {
                                                            torefresh.refresh();
                                                            datas.remove(position);
                                                            mAdapter.notifyDataSetChanged();
                                                            torefresh.refresh();
                                                        }
                                                        showToast(jsonObject.getString("msg"));
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                }

                                @Override
                                public void closeClick() {

                                }
                            });
                        }else {
                            isOrNoDialog.show();
                        }
                        break;
                }

            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                datas.get(position).setMessagesisRead(1);
                intent = new Intent(context, ToEmailActivity.class);
                intent.putExtra("userName", datas.get(position).getUserName());
                intent.putExtra("userId", String.valueOf(datas.get(position).getUserId()));
                intent.putExtra("userImageUrl", datas.get(position).getUserHeadPortraitURL());
                startActivityForResult(intent, 2);
                mAdapter.notifyDataSetChanged();
            }
        });
        refreshMyshupingrecycle.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (toMessageBean.getData().isIsLastPage()) {
                    refreshMyshupingrecycle.finishLoadMore();
                    refreshMyshupingrecycle.setEnableLoadMore(false);
                } else {
                    page++;
                    intdata();
                }

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                datas.clear();
                refreshMyshupingrecycle.setEnableLoadMore(true);
                intdata();
            }
        });
    }

    private void intdata() {
        isIntData=true;
        OkHttpUtils.get(HttpManager.IP + "/person-message")

                .params("startpage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (isfirst) {
                            if (noBackgLodDialog == null) {
                                noBackgLodDialog = new NoBackgLodDialog(context, false);
                            }
                            noBackgLodDialog.show();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (isfirst) {
                            noBackgLodDialog.dismis();
                            isfirst = false;
                        }
                        isIntData=false;
                        Gson gson = new Gson();
                        refreshMyshupingrecycle.finishLoadMore();
                        refreshMyshupingrecycle.finishRefresh();
                        try {
                            toMessageBean = gson.fromJson(s, ToMessageBean.class);
                            if (toMessageBean.getReturnCode() == 200) {
                                datas.clear();
                                datas.addAll(toMessageBean.getData().getList());
                                mAdapter.notifyDataSetChanged();
                                if (datas.size() < 1) {
                                    layout.setVisibility(View.VISIBLE);
                                } else {
                                    layout.setVisibility(View.GONE);
                                }

                            }else if (toMessageBean.getReturnCode() == 400){
                                Intent intent=new Intent(context, LoginActivity.class);
                                startActivity(intent);
                                showToast(toMessageBean.getMsg());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void setTorefresh(Torefresh torefresh) {
        this.torefresh = torefresh;
    }

    public interface Torefresh {
        void refresh();
    }
    public  void refresh(){
        if (!isfirst&&!isIntData){
            page=1;
            intdata();
        }

    }
}
